package nl.samenloop.bigscreen.sequence;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Image;
import java.util.List;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;

import nl.samenloop.bigscreen.Constants;
import nl.samenloop.bigscreen.communication.weather.GoogleWeatherReader;
import nl.samenloop.bigscreen.communication.weather.WeatherInfo;
import nl.samenloop.bigscreen.communication.weather.WeatherModel;

/**
 * 
 * @author Bram Wiekens
 * 
 */
public class WeatherSequence extends Sequence {

	private WeatherModel wm;

	public WeatherSequence(DrawingTarget target) {
		super(target, Constants.WEATHER_TIME);
	}

	@Override
	public void prepare() {
		GoogleWeatherReader gwr = new GoogleWeatherReader(Constants.getProperty(Constants.LOCATION));

		gwr.process();

		wm = gwr.getWeatherModel();

	}

	@Override
	public void start() {
		createForecasts(wm);

		super.start(getTitle(Constants.WEATHER));
	}


	public JComponent createIconLabel(String condition) {
		JPanel c = new JPanel(true);
		c.setBackground(Constants.PURPLE);
		FlowLayout fl = new FlowLayout(FlowLayout.CENTER);
		c.setLayout(fl);

		String path = WeatherInfo.getIconPath(condition);

		ImageIcon icon = new ImageIcon(path);
		
		Image img = icon.getImage();  
		
		int height = icon.getIconHeight() / 2;
		int width = icon.getIconWidth() / 2;
		
		Image newimg = img.getScaledInstance(width, height,  java.awt.Image.SCALE_SMOOTH);  
		ImageIcon newIcon = new ImageIcon(newimg); 
		
		JLabel iconLabel = new JLabel(newIcon);

		c.add(iconLabel);

		return c;
	}

	public void createForecasts(WeatherModel model) {
		List<WeatherModel> forecasts = model.getForecast();

		createForecast("Vandaag", model, 0);

		if (forecasts != null && forecasts.size() > 0) {
			createForecast("Morgen", forecasts.get(0), 1);
		}

	}

	public void createForecast(String time, WeatherModel model, int offset) {
		Container c = target.getCenterContainer();

		JPanel forecastPanel = new JPanel(true);
		forecastPanel.setBackground(Constants.TRANSPARANT);

		BoxLayout bl = new BoxLayout(forecastPanel, BoxLayout.PAGE_AXIS);
		forecastPanel.setLayout(bl);

		String condition = model.getCondition();
		String condNL = WeatherInfo.getNLCondition(condition);

		String temperature = model.getTemperature() + " \u2103";

		forecastPanel.add(createLabel(time, 25,false));
		forecastPanel.add(createIconLabel(condition));
		forecastPanel.add(createLabel(condNL, 25,false));
		forecastPanel.add(createLabel(temperature, 25,false));

		forecastPanel.setBounds(50 + (400 * offset), 10, forecastPanel.getPreferredSize().width,
				forecastPanel.getPreferredSize().height);

		c.add(forecastPanel);

	}

}
